/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Servelt;

import DatabaseAccessing.Customer;
import DatabaseAccessing.CustomerTransaction;
import DatabaseAccessing.ProductModelController;
import DatabaseAccessing.Products;
import DatabaseAccessing.TransactionModelController;
import DatabaseAccessing.UserModelController;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author MaramZahran
 */
public class Signin extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        //response.setContentType("text/html;charset=UTF-8");
       // PrintWriter out = response.getWriter();
        //try {

              /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Signin</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Signin at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
            */
        //} finally {
            //out.close();
       // }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
       //   processRequest(request, response);

        request.getSession().removeAttribute("LOGIN_USER");
        Enumeration e = request.getSession().getAttributeNames();
        while(e.hasMoreElements())
        {
            String s = e.nextElement().toString();
            request.getSession().removeAttribute(s);
        }
        RequestDispatcher rd =null;
        rd=request.getRequestDispatcher("index.jsp");

        rd.include(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        //processRequest(request, response);
        //    PrintWriter out = response.getWriter();
            UserModelController userModelController=new UserModelController();
            RequestDispatcher rd =null;
//          response.setContentType("text/html;charset=UTF-8");
            rd=request.getRequestDispatcher("index.jsp");

            Customer loginUser=userModelController.getUserByEmail(request.getParameter("userName"),request.getParameter("password"));
          
            if(loginUser!=null)
            {
                      request.getSession().setAttribute("LOGIN_USER", loginUser);
                      // response.addCookie(new Cookie("loginInfoCookie",request.getParameter("userName")));
                      request.getSession().setAttribute("loginStatus",0);
                      Object cartObj = request.getSession(false).getAttribute("Cart");
                      List<CustomerTransaction> userCart=null;
                      TransactionModelController tMC = new TransactionModelController();
                      if(cartObj!= null)
                      {
          //                out.println("second not null cart <br>");
                          List<CustomerTransaction> cartList = (List) cartObj;
                          ProductModelController pMC = new ProductModelController();
                          
                           userCart = tMC.getUndoneTransactions(loginUser.getCustomerId());
                          if((cartList!=null)&&(cartList.size()!=0))
                          {
                              boolean added = false;
                              
                              for(int i = 0 ; i < cartList.size();i++)
                              {
                                  added = false;
                                Products p = pMC.viewProductByID(cartList.get(i).getProductId());
                                int amount = p.getAmount();
                                amount--;
                                p.setAmount(amount);
                                pMC.editProduct(p);
                                cartList.get(i).setCustomerId(loginUser.getCustomerId());
                                for(int j = 0 ; j < userCart.size();j++)
                                {
                                    if ((cartList.get(i).getCustomerId()==userCart.get(j).getCustomerId())
                                            && cartList.get(i).getProductId()==userCart.get(j).getProductId())
                                    {
                                        int count = userCart.get(j).getCount();
                                        count++;
                                        userCart.get(j).setCount(count);
                                        tMC.updateTransaction(userCart.get(j));
                                        added = true;
                                        break;
                                    }
                                }
                                if(!added)
                                {
                                   tMC.addTransaction(cartList.get(i));
                                }
                              }
                              request.getSession().removeAttribute("Cart");
                            //  response.sendRedirect("CheckOut.jsp");

                          }
                         
                      }
                      userCart = tMC.getUndoneTransactions(loginUser.getCustomerId());
                      request.getSession().setAttribute("allproductinCarts", userCart);
            }
            else
            {
             request.getSession().setAttribute("loginStatus", 1);
            }


           response.sendRedirect("index.jsp");
          //  rd.forward(request, response);

    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
